import { message } from "antd";
import { ChangeEvent, useEffect, useState } from "react";
import { MAX_FILE_SIZE } from "./const";

export default function useDrag(
  uploadContainerRef: React.RefObject<HTMLDivElement>
) {
  const [selectedFile, setSelectedFile] = useState<File>();
  const [filePreview, setFilePreview] = useState({ url: "", type: "" });
  useEffect(() => {
    if (!selectedFile) return;
    const url = URL.createObjectURL(selectedFile);
    setFilePreview({ url, type: selectedFile.type });
    return () => {
      URL.revokeObjectURL(url);
    };
  }, [selectedFile]);
  function checkFile(files: FileList) {
    const file = files[0];
    if (!file) {
      message.error("没有选择任何文件");
      return;
    }
    //判断文件大小不能超过2G
    if (file.size > MAX_FILE_SIZE) {
      message.error("文件大小不能超过2G");
      return;
    }
    setSelectedFile(file);
  }

  //实现点击上传功能
  useEffect(() => {
    const uploadContainer = uploadContainerRef.current!;
    uploadContainer.addEventListener("click", () => {
      const fileInput = document.createElement("input");
      fileInput.type = "file";
      fileInput.style.display = "none";
      fileInput.addEventListener("change", (event) => {
        const e = event as unknown as ChangeEvent<HTMLInputElement>;
        checkFile(e.target.files!);
      });
      document.body.appendChild(fileInput);
      //手工触发文件的选择
      fileInput.click();
    });
  }, [uploadContainerRef]);
  return { selectedFile, filePreview };
}
